package framework.system.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import framework.core.controller.BaseAction;
import framework.core.util.Kit;
import framework.core.util.ListRange;
import framework.system.entity.SysRole;
import framework.system.entity.SysUser;
import framework.system.entity.front.User;
import framework.system.service.IRoleService;
import framework.system.service.IUserService;

/**
 * @ClassName: UserController 
 * @Description: 用户Controller
 * @author: Ching Wang
 * @date 2013-5-18 下午2:43:48 
 *
 */
@Controller
@RequestMapping("/userctrl")
public class UserController extends BaseAction {
	
	@Resource private IUserService userService;
	@Resource private IRoleService roleService;
	
	/**
	 * @Title: loadUser 
	 * @Description: 加载登陆用户信息
	 * @param session
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/loadUser")
	public void loadUser(HttpSession session, HttpServletResponse response) throws Exception{
		JSONObject obj = new JSONObject();
		SysUser sysUser = (SysUser) session.getAttribute("user");
		if(sysUser != null){
			SysUser u = userService.getUser(sysUser.getId());
			User user = new User();
			BeanUtils.copyProperties(u, user);
			Set<SysRole> sysRoles = u.getSysRoles();
			 if(sysRoles != null && sysRoles.size() > 0){
				List<String> roleIds = new ArrayList<String>();
				List<String> roleNames = new ArrayList<String>();
				 for(SysRole sysRole : sysRoles){
					 roleIds.add("'"+sysRole.getId()+"'");
					 roleNames.add(sysRole.getName());
				 }
				 user.setRoleIds(roleIds);
				 user.setRoleNames(roleNames);
			 }
			 
			obj.put("success", true);
			obj.put("user", user);
		}
		else{
			obj.put("success", false);
			obj.put("user", "获取用户信息失败，请确认！");
		}
		outJson(response, obj, "yyyy-MM-dd");
	}
	
	/**
	 * @Title: editUser 
	 * @Description: 编辑用户信息
	 * @param user 用户属性集合
	 * @param oper 操作类型（add：添加，edit：更新）
	 * @param session
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/editUser")
	public void editUser(User user, String oper, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception{
		SysUser sysUser = new SysUser();
		if(Kit.isNotNull(user.getId())){
			sysUser = userService.getUser(user.getId());
		}
		else{
			sysUser.setName(user.getName());
			sysUser.setAccount(user.getAccount());
			sysUser.setPassword(Kit.getMd5("111111"));
		}
		
		if(Kit.isNotNull(oper) && ("add".equals(oper) || "edit".equals(oper))){
			if(user.getRoleIds() != null && user.getRoleIds().size() > 0){
				Set<SysRole> sysRoles = new HashSet<SysRole>();
				for(String str : user.getRoleIds()){
					SysRole sysRole = roleService.getRole(str);
					sysRoles.add(sysRole);
				}
				sysUser.setSysRoles(sysRoles);
			}
		}
		sysUser.setEmail(user.getEmail());
		sysUser.setAddress(user.getAddress());
		sysUser.setMobile(user.getMobile());
		sysUser.setRemark(user.getRemark());
		userService.saveOrUpdate(sysUser);
		JSONObject obj = new JSONObject();
		obj.put("success", true);
		if(Kit.isNotNull(oper) && "add".equals(oper)){
			obj.put("message", "添加用户信息成功。");
		}
		if(Kit.isNotNull(oper) && "edit".equals(oper)){
			obj.put("message", "更新用户信息成功。");
		}
		if(Kit.isNotNull(oper) && "personal".equals(oper)){
			obj.put("message", "更新个人信息成功。");
		}
		outJson(response, obj, "yyyy-MM-dd");
	}
	
	/**
	 * @Title: updatePass 
	 * @Description: 修改密码
	 * @param oldpass 原始密码
	 * @param newpass 新密码
	 * @param checkpass 确认密码
	 * @param session
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/updatePass")
	public void updatePass(String oldpass, String newpass, String checkpass, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception{
		JSONObject obj = new JSONObject();
		if(Kit.isNotNull(newpass)){
			if(checkpass.equals(newpass)){
				SysUser sysUser = (SysUser) session.getAttribute("user");
				if (sysUser != null) {
					SysUser user = userService.getUser(sysUser.getId());
					if(Kit.getMd5(oldpass).equals(user.getPassword())){
						user.setPassword(Kit.getMd5(newpass));
						userService.saveOrUpdate(user);
						obj.put("success", true);
						obj.put("message", "修改密码成功。");
					}
					else{
						obj.put("success", false);
						obj.put("message", "原始密码不正确，请确认。");
					}
				}
				else{
					obj.put("success", false);
					obj.put("message", "用户未登陆，请确认。");
				}
			}
			else{
				obj.put("success", false);
				obj.put("message", "两次输入密码不一致，请确认。");
			}
		}
		else{
			obj.put("success", false);
			obj.put("message", "新密密码不能为空，请确认。");
		}
		outJson(response, obj, "yyyy-MM-dd");
	}
	
	/**
	 * @Title: listUser 
	 * @Description: 查询用户列表
	 * @param userName 用户姓名
	 * @param userAcc 用户帐号
	 * @param page 第page页
	 * @param rows 获取rows行
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/listUser")
	public void listUser(String userName, String userAcc, String page, String rows, HttpServletRequest request, HttpServletResponse response) throws Exception{
		ListRange<User> range = new ListRange<User>();
		List<User> users = new ArrayList<User>();
		Set<SysRole> sysRoles = null;
		User user = null;
		DetachedCriteria criteria = DetachedCriteria.forClass(SysUser.class);
		if(Kit.isNotNull(userName)){
			criteria.add(Restrictions.like("name", userName, MatchMode.ANYWHERE));
		}
		if(Kit.isNotNull(userAcc)){
			criteria.add(Restrictions.like("account", userAcc, MatchMode.ANYWHERE));
		}
		
		long total = userService.getCount(criteria);
		if(total > 0){
			List<SysUser> sysUsers =  userService.listUser(criteria, page, rows);
			for(SysUser sysUser : sysUsers){
				 user = new User();
				 BeanUtils.copyProperties(sysUser, user);
				 sysRoles = sysUser.getSysRoles();
				 if(sysRoles != null && sysRoles.size() > 0){
					 List<String> roleIds = new ArrayList<String>();
					 List<String> roleNames = new ArrayList<String>();
					 for(SysRole sysRole : sysRoles){
						 roleIds.add(sysRole.getId());
						 roleNames.add(sysRole.getName());
					 }
					 user.setRoleIds(roleIds);
					 user.setRoleNames(roleNames);
				 }
				 users.add(user);
			}
		}
		range.setRows(users);
		range.setTotal(total);
		outJson(response, range, "yyyy-MM-dd");
	}
	
	/**
	 * @Title: delUser 
	 * @Description: 删除用户信息
	 * @param userIds 用户ID集合
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/delUser")
	public void delUser(String userIds, HttpServletRequest request, HttpServletResponse response) throws Exception{
		ListRange<User> range = new ListRange<User>();
		boolean flag = false;
		if(Kit.isNotNull(userIds)){
			flag = userService.delUser(userIds.split(","));
		}
		else{
			range.setMessage("未找到相关用户，请确认.");
		}
		if(flag){
			range.setMessage("删除用户信息成功.");
		}
		range.setSuccess(flag);
		outJson(response, range, "yyyy-MM-dd");
	}
	
	/**
	 * @Title: isExist 
	 * @Description: 判断账号是否存在 
	 * @param account 用户帐号
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/isExist")
	public void isExist(String account, HttpServletRequest request, HttpServletResponse response) throws Exception{
		JSONObject object = new JSONObject();
		DetachedCriteria criteria = DetachedCriteria.forClass(SysUser.class);
		criteria.add(Restrictions.eq("account", account));
		long count = userService.getCount(criteria);
		if(count > 0){
			object.put("success", true);
		}
		else{
			object.put("success", false);
		}
		outJson(response, object, "yyyy-MM-dd");
	}
}
